use std::cell::RefCell;
use std::fs::File;
use std::io::Read;
use std::ops::Deref;

use crate::class_path::class_file_packet::ClassFilePacket;

pub struct JmodClassFilePacket {
    pub jmod_file_path: RefCell<String>,
}


impl ClassFilePacket for JmodClassFilePacket {
    fn read_class(&self, class_name: &String) -> Result<Vec<u8>, String> {
        let zip_file = File::open(self.jmod_file_path.borrow().deref()).unwrap();
        let mut zip_archive = zip::ZipArchive::new(zip_file).unwrap();

        let zip_class_name = format!("classes/{}.class", class_name);

        for index in 0..zip_archive.len() {
            let mut file = zip_archive.by_index(index).unwrap();
            if zip_class_name.as_str().eq(file.name()) {
                let mut data: Vec<u8> = Vec::new();
                let read_result = file.read_to_end(&mut data);
                return match read_result {
                    Ok(_size) =>{
                        Ok(data)
                    }
                    Err(err) => {
                        Err(err.to_string())
                    }
                }
            }
        }
        return Err(String::from("Class Not Found"));
    }

    fn to_string(&self) -> String {
        return format!("JmodFileClassFilePacket[{}]", self.jmod_file_path.borrow());
    }
}